/*
 * @Descripttion:
 * @LastEditors: xzh
 * @LastEditTime: 2024-07-02 01:34:34
 */
import router from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { ElMessage } from "element-plus";
import { RouteRecordRaw } from "vue-router";
import { object_Inf } from "@/utils/typings/index.type";
import Dile_StoreAction from "@storeAction/index";
import Dile_Methods from "@/utils/methods";
import Cookies_Token from "@/utils/cache/cookies/token";
import Dile_Constants from "@/utils/constants/app";

NProgress.configure({ showSpinner: false });

const whiteList = ["/login", "/afterSale"];

/**
 * @Author: xzh
 * @Descripttion:判断无界是否初始化加载
 * @Param:
 * @param {string} path
 */
let wujieFirstLoad = (path: string) => {
  let { isActivate } = window.$wujie || {};
  // 在无界中为子应用 && 地址主页 && 无界未激活
  return !!window.__POWERED_BY_WUJIE__ && path == "/console" && !isActivate;
};

router.beforeEach(async (to: any, _: any, next: any) => {
  //判断无界是否初始化加载
  if (!!wujieFirstLoad(to.path)) {
    next({ path: "/wujieEmpty" });
  } else {
    // Start progress bar
    NProgress.start();
    if (whiteList.includes(to.path)) {
      // In the free login whitelist, go directly
      next();
    } else {
      //获取用户token
      let token = new Cookies_Token().get();
      if (!!token || !!window.__POWERED_BY_WUJIE__) {
        if (!!whiteList.includes(to.path)) {
          // If is logged in, redirect to the home page
          next({ path: "/" });
          NProgress.done();
        } else {
          let hasGetUserInfo = Dile_StoreAction.currentUserInfo()!.userName;
          if (
            (!!hasGetUserInfo && !!to.name) ||
            !!window.__POWERED_BY_WUJIE__
          ) {
            //兼容根节点路由刷新后跳转
            let layoutPath = Dile_StoreAction.compatibleRootRouterRefresh(to);
            //根节点跳转match错误时，跳转layout
            !!layoutPath && !window.__POWERED_BY_WUJIE__
              ? next({ path: layoutPath })
              : next();
          } else {
            try {
              // 获取用户信息
              const { account } = await Dile_StoreAction.getUserInfo();
              // 基于角色生成可访问路由图;
              const accessRoutes: Array<object_Inf> = [
                //基于角色生成可访问路由图
                ...(await Dile_StoreAction.generateRoutes(account || "")),
                //拼接路由历史中静态路由
                Dile_Methods.jointStaticRouterHistory(),
              ];
              accessRoutes.forEach((item: object_Inf) =>
                // 动态添加可访问路由
                router.addRoute(item as RouteRecordRaw)
              );
              //格式化根路由节点layout
              // Dile_StoreAction.formatRootRoutetLayout();
              //判断当前跳转路由是否存在
              !router.getRoutes().find((x) => x.path == to.path)
                ? next({ path: `/${Dile_Constants.sideBarMap.homePage}` })
                : // 设置replace:true，这样导航就不会留下历史记录
                  next({ ...to, replace: true });
            } catch (error: any) {
              // 删除token并转到登录页面重新登录
              await Dile_StoreAction.resetToken();
              ElMessage.error(error.message || error || "Has Error");
              next(`/login?redirect=${to.path}`);
              NProgress.done();
            }
          }
        }
      } else {
        // Has no token

        // Other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  }
});

router.afterEach(async (to: any) => {
  // Finish progress bar
  NProgress.done();
  // //获取当前语言字段
  // let field = Dile_Constants.languageKey();
  // // 获取当前语言 设置 page title
  // document.title = to.meta[field];
});
